package com.ai.platform.system.service.impl;

import com.ai.platform.common.util.AiPlatformUtil;
import com.ai.platform.core.exception.BusinessException;
import com.ai.platform.model.dto.Input;
import com.ai.platform.model.dto.Output;
import com.ai.platform.system.entity.SysRole;
import com.ai.platform.system.entity.SysUser;
import com.ai.platform.system.mapper.SysRoleMapper;
import com.ai.platform.system.service.ISysRoleService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yeyingsheng
 * @since 2018-05-12
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Override
    public void queryRoleByUserId(Input input, Output output) throws BusinessException {
        Integer userId = Integer.parseInt(input.getValue("userId"));
        try {
            List<SysRole> roles = baseMapper.queryRoleByUserId(userId);
            output.setData(roles);
        } catch (SQLException e) {
            throw new BusinessException("SQL异常:" + e.getMessage());
        }
    }

    @Override
    public void listRoleAll(Input input, Output output) throws BusinessException {
        //查询所有角色
        List<SysRole> roles = baseMapper.selectList(new EntityWrapper<SysRole>().orderBy("order_no", true));
        //查询我拥有的角色
        SysUser user= (SysUser) AiPlatformUtil.getSessionObj(input,SysUser.class);
        List<SysRole> myRoles = null;
        try {
            myRoles = baseMapper.queryRoleByUserId(user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            for (SysRole role : roles) {
                boolean isChecked = false;
                if (!CollectionUtils.isEmpty(myRoles)) {
                    for (SysRole myRole : myRoles) {
                        if (String.valueOf(role.getId()).equals(String.valueOf(myRole.getId()))) {
                            isChecked = true;
                            break;
                        }
                    }
                }
                Map<String, Object> map = new HashMap<>();
                map.put("id", role.getId());
                map.put("name", role.getName());
                map.put("checked", isChecked);
                resultList.add(map);
            }
        }
        output.setData(resultList);
    }
}
